
const { default: router, asyncRoutes } = require('./router')
const { default: store } = require('./store')
// 添加进度条提高用户体验
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from './utils/get-page-title'
// NProgress.configure({ showSpinner: false }) // NProgress Configuration
const whiteList = ['/login', '/404']
// const whiteList = ['/login'] // no redirect whitelist
// 设置路由前置守卫控制权限
router.beforeEach(async(to, from, next) => {
  // 跳转前就开启进度条
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  // 根据是否有token判断
  const token = store.state.user.token
  if (token) {
    if (to.path === '/login') {
      // 已经登录就别去登录
      next('/')
      NProgress.done()
    } else {
      // 判断是否已经有用户信息
      if (!store.state.user.userInfo.userId) {
        // 放行就发送请求获取详细数据
        const menusList = await store.dispatch('user/getUser')
        const filterRoutes = asyncRoutes.filter(route => {
          return menusList.includes(route.children[0].name)
        })
        router.addRoutes(filterRoutes)
        // 处理刷新404
        filterRoutes.push({ path: '*', redirect: '/404', hidden: true })
        // 为了渲染页面需要将动态路由存在vuex中
        store.commit('menus/setMenus', filterRoutes)
        next({ ...to, replace: true })
      } else {
        next()
      }
    }
  } else {
    // 根据白名单判断
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach((to, from, next) => {
  // 完成跳转后就关闭进度条
  NProgress.done()
})

